package com.tfswx.jcyw.sqlmodel.gic.operators;

import com.alibaba.fastjson.JSON;
import com.tfswx.jcyw.sqlmodel.api.Operator;
import com.tfswx.jcyw.sqlmodel.api.bean.Node;
import com.tfswx.jcyw.sqlmodel.api.bean.jdpz.UnionJdpz;
import com.tfswx.jcyw.sqlmodel.api.bean.table.*;
import com.tfswx.jcyw.sqlmodel.api.bean.table.expression.Column;

import java.util.List;

/**
 * @author 张述江
 * @date 2023/9/7
 */
public class DefaultUnionOperator implements Operator {
    @Override
    public String getName() {
        return "合并";
    }

    @Override
    public Select operate(Node node, List<Select> pResultList) {
        System.out.println("执行了" + getName() + "操作");

        Select t0 = pResultList.get(0);
        Select t1 = pResultList.get(1);

        PlainSelect parenthesedSelect = new PlainSelect(new ParenthesedSelect(t0));
        PlainSelect parenthesedSelect1 = new PlainSelect(new ParenthesedSelect(t1));
        
        UnionJdpz unionJdpz = JSON.parseObject(node.getJdpz(), UnionJdpz.class);

        for (UnionJdpz.HbzdItem hbzdItem : unionJdpz.getHbzdList()) {
            String zdmc1 = hbzdItem.getZdmc1();
            String zdmc2 = hbzdItem.getZdmc2();
            String zdmc = hbzdItem.getZdmc();
            parenthesedSelect.addSelectItem(new SelectItem(new Column(zdmc1), new Alias(zdmc)));
            parenthesedSelect1.addSelectItem(new SelectItem(new Column(zdmc2), new Alias(zdmc)));
        }

        SetOperationList setOperationList = new SetOperationList(parenthesedSelect);
        setOperationList.addSelect(new UnionOperation(), parenthesedSelect1);

        return setOperationList;
    }
}
